#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int sockfd;
    sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd==-1)
    {
        cout<<"SOCKET created is false"<<endl;
        return -1;
    }

    struct sockaddr_in serrver_addr;
    serrver_addr.sin_family=AF_INET;
    serrver_addr.sin_port=htons(5000);
    serrver_addr.sin_addr.s_addr=inet_addr("192.168.1.63");
    if(bind(sockfd,(const struct sockaddr *)(&serrver_addr),sizeof(serrver_addr))==-1)
    {
        cout<<"binded is false"<<endl;
        return -2;
    }

    char buf[128];
    int client1Port=5001;
    struct sockaddr_in client_addr[2];
    client_addr[0].sin_family=AF_INET;
    client_addr[0].sin_port=htons(client1Port);
    client_addr[0].sin_addr.s_addr=inet_addr("192.168.1.63");
    int client2Port=5002;
    client_addr[1].sin_family=AF_INET;
    client_addr[1].sin_port=htons(client2Port);
    client_addr[1].sin_addr.s_addr=inet_addr("192.168.1.63");
    socklen_t fromlen=sizeof(client_addr);

    while(1)
    {
        buf[0]='l';
        sendto(sockfd,buf,128,0,(struct sockaddr *)(&client_addr[0]),128);
        cout<<"send the message "<<buf<<" to "<<client1Port<<endl;
        buf[0]='k';
        sendto(sockfd,buf,128,0,(struct sockaddr *)(&client_addr[1]),128);
        cout<<"send the message "<<buf<<"to "<<client2Port<<endl;

        recvfrom(sockfd,buf,128,0,(struct sockaddr *)(&client_addr[0]),&fromlen);
        cout<<"the message is from "<<client1Port<<endl;
        cout<<"the message received is "<<buf<<endl;
        recvfrom(sockfd,buf,128,0,(struct sockaddr *)(&client_addr[1]),&fromlen);
        cout<<"the message is from "<<client2Port<<endl;
        cout<<"the message received is "<<buf<<endl;
        sleep(1);
    }
    close(sockfd);
    return 0;
}
